﻿@inject IUserService UserService
@inject IRoleService RoleService
@inject DialogService DialogService
@inject NotificationService NotificationService

<RadzenStack AlignItems="AlignItems.Start" Wrap="FlexWrap.Wrap">
    <RadzenStack class="rz-mb-2" Style="width:100%;">
        <RadzenRow>
            <RadzenColumn Size="12" SizeSM="12">
                <RadzenFormField Text="搜索用户" Style="width:100%;">
                    <RadzenAutoComplete @bind-Value=@AutoCurrentUser LoadData=@OnLoadData Data="_users"
                                        TextProperty="UserName" Style="width:100%;">
                        <Template>
                            <RadzenRow>
                                <RadzenColumn>
                                    <RadzenImage Path="@context.Avatar" class="rz-gravatar" />
                                </RadzenColumn>
                                <RadzenColumn>@context.UserName</RadzenColumn>
                            </RadzenRow>
                        </Template>
                    </RadzenAutoComplete>
                </RadzenFormField>
            </RadzenColumn>
        </RadzenRow>
    </RadzenStack>
    <RadzenStack Orientation="Orientation.Horizontal" JustifyContent="JustifyContent.End" Style="width:100%;">
        <RadzenButton ButtonStyle="ButtonStyle.Light" Text="Cancel" Variant="Variant.Flat" Click="@CancelButtonClick" />
        <RadzenButton ButtonStyle="ButtonStyle.Primary" Click="SubmitButtonClick"
                      ButtonType="ButtonType.Submit" Icon="save" Text="Save" Variant="Variant.Flat" />
    </RadzenStack>
</RadzenStack>

@code {
    protected string AutoCurrentUser;
    private IEnumerable<UserInfoResponseDto> _users;


    [Parameter]
    public Guid RoleId { get; set; }

    async Task OnLoadData(LoadDataArgs args)
    {
        var result = await UserService.QueryUsers(new UserSearchRequestDto()
            {
                UserName = args.Filter
            });

        if (result.Succeeded)
        {
            _users = result.Data;
        }

    }

    void CancelButtonClick()
    {
        DialogService.Close();
    }

    async Task SubmitButtonClick()
    {
        if (AutoCurrentUser == null)
        {
            return;
        }

        var result = await RoleService.UpdateUsersByRole(RoleId, new RoleOperateRequestDto()
            {
                OperateType = "Add",
                UserNames = new List<string>() { AutoCurrentUser }
            });

        if (result.Succeeded)
        {
            NotificationService.Notify(new NotificationMessage
                {
                    Severity = NotificationSeverity.Success,
                    Summary = "提示",
                    Detail = "保存成功",
                    Duration = 4000
                });
            DialogService.Close();
        }
    }

}